package cn.gayaguoguo.guohealthindicator.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

import com.google.common.base.Charsets;

public class FileConfig {
	
	/**
	 * @author GayaGuoguo
	 * 方便的多配置文件包装类
	 */
	
	private FileConfiguration config = null;
	
	private File configFile = null;
	
	private Plugin instance;

	private String fileName;
	
	/**
	 * 从插件内部抽取数据，生成一个yml文件
	 * @param fileName 需要生成文件名，例如 data.yml
	 */
	public FileConfig(String fileName, Plugin instance){
		this.fileName = fileName;
		this.instance = instance;
		if (configFile == null){
			configFile = new File(instance.getDataFolder(), this.fileName);
		}
		if (!configFile.exists()){
			instance.saveResource(this.fileName, false);
		}
	}
	
	/**
	 * 获取FileConfiguration对象，相当于bukkit的getConfig();
	 * @return
	 */
	public FileConfiguration get(){
		if (config == null){
			reload();
		}
		return config;
	}

	/**
	 * 重新读取文件
	 */
	public void reload() {
		if (configFile == null) {
			configFile = new File(instance.getDataFolder(), fileName);
		}
		config = YamlConfiguration.loadConfiguration(configFile);
		Reader defConfigStream = new InputStreamReader(instance.getResource(fileName), Charsets.UTF_8);
		if (defConfigStream != null) {
			YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
			config.setDefaults(defConfig);
		}
	}

	/**
	 * 将数据写入文件
	 */
	public void save() {
		if (config == null || configFile == null) {
			return;
		}
		try {
			config.save(configFile);
		} catch (IOException ex) {
		}
	}
}
